package qingxin.servlet.client.comment;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import qingxin.dao.NewsCommentDAO;
import qingxin.factory.DAOFactory;

@WebServlet("/client/comment/add")
public class AdditionServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private NewsCommentDAO newsCommentDAO;
	
	public AdditionServlet(){
		super();
		newsCommentDAO = DAOFactory.getNewsCommentDAO();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		try{
			int newsID = Integer.parseInt(request.getParameter("nid"));
			int userID = Integer.parseInt(request.getParameter("uid"));
			
			String comment = request.getParameter("comment");
			Date now = new Date();
			DateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); 
			String date = df.format(now);
			
			newsCommentDAO.add(newsID, userID, comment, date);
			
			writer.println("{\"msg\":\"ok\"}");
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}
